﻿using Kxx_API.DNS.ALI.DataModel;
using Kxx_Common.Tools;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tea;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace Kxx_API.DNS.ALI.Helper
{
    public class CDNSHelper
    {
        public CDNSHelper(string accessKeyId, string accessKeySecret, string endpoint)
        {
            this.accessKeyId = accessKeyId;
            this.accessKeySecret = accessKeySecret;
            this.endpoint = endpoint;
        }

        #region 字段
        private string accessKeyId { get; set; }
        private string accessKeySecret { get; set; }

        /// <summary>
        /// 访问dns域名
        /// </summary>
        private string endpoint { get; set; }

        /// <summary>
        /// 是否存在错误
        /// </summary>
        private bool isErr = false;
        public bool IsErr
        {
            get { return isErr; }
            set { isErr = value; }
        }

        /// <summary>
        /// 错误信息
        /// </summary>
        private string errMsg;
        public string ErrMsg
        {
            get { return errMsg; }
            set { errMsg = value; }
        }
        #endregion

        #region 连接初始化
        private readonly static object obj = new object();
        private static AlibabaCloud.SDK.Alidns20150109.Client aliClient;

        /// <summary>
        /// 初始化账号Client
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        private AlibabaCloud.SDK.Alidns20150109.Client ClientInit()
        {
            if (accessKeyId.IsEmpty() || accessKeySecret.IsEmpty() || endpoint.IsEmpty())
            {
                return null;
            }

            AlibabaCloud.SDK.Alidns20150109.Client client;

            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
            {
                AccessKeyId = accessKeyId,
                AccessKeySecret = accessKeySecret,
            };
            config.Endpoint = endpoint;

            try
            {
                client = new AlibabaCloud.SDK.Alidns20150109.Client(config);
            }
            catch (Exception e)
            {
                ExistsErr(e.Message);
                return null;
            }

            ClearErr();
            return client;
        }

        /// <summary>
        /// 获取账号Client
        /// </summary>
        public AlibabaCloud.SDK.Alidns20150109.Client GetClient
        {
            get
            {
                if (aliClient == null)
                {
                    lock (obj)
                    {
                        if (aliClient == null)
                        {
                            aliClient = ClientInit();
                        }
                    }
                }

                ClearErr();
                return aliClient;
            }
        }
        #endregion

        #region 账号Client刷新
        /// <summary>
        /// 账号Client刷新
        /// </summary>
        public void ClientRefresh()
        {
            aliClient = ClientInit();
        }
        #endregion

        #region 错误信息
        /// <summary>
        /// 存在错误
        /// </summary>
        /// <param name="errMsg"></param>
        private void ExistsErr(string errMsg)
        {
            IsErr = true;
            ErrMsg = errMsg;
        }

        /// <summary>
        /// 清除错误
        /// </summary>
        private void ClearErr()
        {
            IsErr = false;
            ErrMsg = "";
        }
        #endregion

        #region 获取域名
        /// <summary>
        /// 获取所有域名信息（按页码及页大小缓存，默认300秒）
        /// </summary>
        /// <param name="pageNumber">页码</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="isNew">是否获取最新</param>
        /// <returns></returns>
        public PageBaseDataModel<DomainDataModel> GetDNSList(long pageNumber, long pageSize, bool isNew = false)
        {
            PageBaseDataModel<DomainDataModel> t = new PageBaseDataModel<DomainDataModel>();

            #region 请求DNS列表
            //账号Client为空时
            if (GetClient == null)
            {
                ExistsErr(AlibabaCloud.TeaUtil.Common.AssertAsString("账号Client初始化失败!"));
                return null;
            }

            //域名列表请求
            AlibabaCloud.SDK.Alidns20150109.Models.DescribeDomainsRequest describeDomainsRequest = new AlibabaCloud.SDK.Alidns20150109.Models.DescribeDomainsRequest
            {
                PageNumber = pageNumber,
                PageSize = pageSize
            };

            //域名列表结果
            AlibabaCloud.SDK.Alidns20150109.Models.DescribeDomainsResponse res = null;

            try
            {
                // 复制代码运行请自行打印 API 的返回值
                res = GetClient.DescribeDomains(describeDomainsRequest);
            }
            catch (TeaException error)
            {
                aliClient = null;
                ExistsErr(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));

                return null;
            }
            catch (Exception _error)
            {
                TeaException error = new TeaException(new Dictionary<string, object>
                {
                    { "message", _error.Message }
                });
                ExistsErr(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));

                return null;
            }
            #endregion

            #region 解析结果
            string resJson = ConvertJson.SerializeObject(res.Body);

            try
            {
                t = ConvertJson.DeserializeJsonToObject<PageBaseDataModel<DomainDataModel>>(resJson);
            }
            catch (Exception e)
            {
                ExistsErr(e.Message);
                return null;
            }
            #endregion

            return t;
        }
        #endregion

        #region 获取域名解析记录
        /// <summary>
        /// 获取域名解析记录
        /// </summary>
        /// <param name="domainName">域名名称</param>
        /// <param name="pageNumber">页码</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="isNew">是否获取最新</param>
        /// <returns></returns>
        public PageBaseDataModel<DomainRecordDataModel> GetDomainRecord(string domainName, long pageNumber, long pageSize, bool isNew = false)
        {
            PageBaseDataModel<DomainRecordDataModel> t = new PageBaseDataModel<DomainRecordDataModel>();

            #region 请求DNS列表
            //账号Client为空时
            if (GetClient == null)
            {
                ExistsErr(AlibabaCloud.TeaUtil.Common.AssertAsString("账号Client初始化失败!"));
                return null;
            }

            //域名解析记录列表请求
            AlibabaCloud.SDK.Alidns20150109.Models.DescribeDomainRecordsRequest describeDomainRecordsRequest = new AlibabaCloud.SDK.Alidns20150109.Models.DescribeDomainRecordsRequest
            {
                DomainName = domainName,
                PageNumber = pageNumber,
                PageSize = pageSize
            };

            //域名解析记录列表结果
            AlibabaCloud.SDK.Alidns20150109.Models.DescribeDomainRecordsResponse res = null;

            try
            {
                // 复制代码运行请自行打印 API 的返回值
                res = GetClient.DescribeDomainRecords(describeDomainRecordsRequest);
            }
            catch (TeaException error)
            {
                aliClient = null;
                ExistsErr(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));

                return null;
            }
            catch (Exception _error)
            {
                TeaException error = new TeaException(new Dictionary<string, object>
                {
                    { "message", _error.Message }
                });
                ExistsErr(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));

                return null;
            }
            #endregion

            #region 解析结果
            string resJson = ConvertJson.SerializeObject(res.Body);

            try
            {
                t = ConvertJson.DeserializeJsonToObject<PageBaseDataModel<DomainRecordDataModel>>(resJson);
            }
            catch (Exception e)
            {
                ExistsErr(e.Message);
                return null;
            }
            #endregion

            return t;
        }
        #endregion

        #region 获取解析记录详细
        /// <summary>
        /// 获取解析记录详细
        /// </summary>
        /// <param name="recordId">解析记录的ID</param>
        /// <returns></returns>
        public DomainRecordDetailsDataModel GetDomainRecordDetails(string recordId)
        {
            DomainRecordDetailsDataModel model;

            #region 请求DNS列表
            //账号Client为空时
            if (GetClient == null)
            {
                ExistsErr(AlibabaCloud.TeaUtil.Common.AssertAsString("账号Client初始化失败!"));
                return null;
            }

            //更新解析记录请求
            AlibabaCloud.SDK.Alidns20150109.Models.DescribeDomainRecordInfoRequest updateDomainRecordRequest = new AlibabaCloud.SDK.Alidns20150109.Models.DescribeDomainRecordInfoRequest
            {
                RecordId = recordId
            };

            //更新解析记录结果
            AlibabaCloud.SDK.Alidns20150109.Models.DescribeDomainRecordInfoResponse res = null;

            try
            {
                // 复制代码运行请自行打印 API 的返回值
                res = GetClient.DescribeDomainRecordInfo(updateDomainRecordRequest);
            }
            catch (TeaException error)
            {
                aliClient = null;
                ExistsErr(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));

                return null;
            }
            catch (Exception _error)
            {
                TeaException error = new TeaException(new Dictionary<string, object>
                {
                    { "message", _error.Message }
                });
                ExistsErr(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));

                return null;
            }
            #endregion

            #region 解析结果
            string resJson = ConvertJson.SerializeObject(res.Body);

            try
            {
                model = ConvertJson.DeserializeJsonToObject<DomainRecordDetailsDataModel>(resJson);
            }
            catch (Exception e)
            {
                ExistsErr(e.Message);
                return null;
            }
            #endregion

            return model;
        }
        #endregion

        #region 更新解析记录
        /// <summary>
        /// 更新解析记录
        /// </summary>
        /// <param name="recordId">解析记录的ID</param>
        /// <param name="rr">主机记录</param>
        /// <param name="type">解析记录类型</param>
        /// <param name="value">记录值</param>
        /// <returns></returns>
        public bool UpdateDomainRecord(string recordId, string rr, string type, string value)
        {
            #region 请求DNS列表
            //账号Client为空时
            if (GetClient == null)
            {
                ExistsErr(AlibabaCloud.TeaUtil.Common.AssertAsString("账号Client初始化失败!"));
                return false;
            }

            //更新解析记录请求
            AlibabaCloud.SDK.Alidns20150109.Models.UpdateDomainRecordRequest updateDomainRecordRequest = new AlibabaCloud.SDK.Alidns20150109.Models.UpdateDomainRecordRequest
            {
                RecordId = recordId,
                RR = rr,
                Type = type,
                Value = value
            };

            //更新解析记录结果
            AlibabaCloud.SDK.Alidns20150109.Models.UpdateDomainRecordResponse res = null;

            try
            {
                // 复制代码运行请自行打印 API 的返回值
                res = GetClient.UpdateDomainRecord(updateDomainRecordRequest);
            }
            catch (TeaException error)
            {
                aliClient = null;
                ExistsErr(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));

                return false;
            }
            catch (Exception _error)
            {
                TeaException error = new TeaException(new Dictionary<string, object>
                {
                    { "message", _error.Message }
                });
                ExistsErr(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));

                return false;
            }
            #endregion

            #region 解析结果
            //string resJson = ConvertJson.SerializeObject(res.Body);

            //try
            //{
            //    t = ConvertJson.DeserializeJsonToObject<PageBaseDataModel<DomainDataModel>>(resJson);
            //}
            //catch (Exception e)
            //{
            //    ExistsErr(e.Message);
            //    return null;
            //}
            #endregion

            return true;
        }
        #endregion
    }
}
